<template>
  <div class="login-bg">
    <div class="login-card">
      <h2 class="login-title">{{ isLogin ? '登录' : '注册' }}</h2>
      <!-- 登录表单 -->
      <el-form v-if="isLogin" @submit.prevent="handleLogin" class="login-form" label-width="80px">
        <el-form-item label="学号/工号">
          <el-input v-model="userId" placeholder="请输入学号或工号" class="login-input" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="password" type="password" placeholder="请输入密码" class="login-input" />
        </el-form-item>
        <el-form-item label="身份">
          <el-radio-group v-model="role">
            <el-radio label="student">学生</el-radio>
            <el-radio label="teacher">教师</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleLogin" class="login-btn">登录</el-button>
          <el-button @click="toggleMode" class="login-btn">去注册</el-button>
        </el-form-item>
      </el-form>
      <!-- 注册表单 -->
      <el-form v-else @submit.prevent="handleRegister" class="login-form" label-width="80px">
        <el-form-item label="学号/工号">
          <el-input v-model="registerForm.userId" placeholder="请输入学号或工号" class="login-input" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="registerForm.name" placeholder="请输入姓名" class="login-input" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="registerForm.password" type="password" placeholder="请输入密码" class="login-input" />
        </el-form-item>
        <el-form-item label="确认密码">
          <el-input v-model="registerForm.confirmPassword" type="password" placeholder="请再次输入密码" class="login-input" />
        </el-form-item>
        <el-form-item label="身份">
          <el-radio-group v-model="registerForm.role">
            <el-radio label="student">学生</el-radio>
            <el-radio label="teacher">教师</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleRegister" class="login-btn">注册</el-button>
          <el-button @click="toggleMode" class="login-btn">去登录</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { useUserStore } from '../store/user'

const userId = ref('')
const password = ref('')
const role = ref('student')
const router = useRouter()
const userStore = useUserStore()

// 注册相关状态
const isLogin = ref(true)
const registerForm = ref({
  userId: '',
  name: '',
  password: '',
  confirmPassword: '',
  role: 'student'
})

// 切换登录/注册模式
const toggleMode = () => {
  isLogin.value = !isLogin.value
  // 清空表单
  if (isLogin.value) {
    registerForm.value = {
      userId: '',
      name: '',
      password: '',
      confirmPassword: '',
      role: 'student'
    }
  } else {
    userId.value = ''
    password.value = ''
    role.value = 'student'
  }
}

const handleLogin = async () => {
  if (!userId.value || !password.value) {
    alert('请输入完整信息')
    return
  }
  try {
    const res = await axios.post('/api/login', {
      userId: userId.value,
      password: password.value,
      role: role.value
    })
    if (res.data.code === 200) {
      // 存储用户信息到 store
      userStore.setUserInfo(res.data.data)
      
      // 存储到 localStorage 作为备用
      localStorage.setItem('userId', res.data.data.userId)
      localStorage.setItem('role', res.data.data.role)
      localStorage.setItem('name', res.data.data.name)
      localStorage.setItem('token', res.data.data.token)
      localStorage.setItem('studentId', res.data.data.studentId || '')
      localStorage.setItem('teacherId', res.data.data.teacherId || '')
      
      if (res.data.data.role === 'student') {
        router.push('/student')
      } else if (res.data.data.role === 'teacher') {
        router.push('/teacher')
      }
    } else {
      alert(res.data.msg || '登录失败')
    }
  } catch (error) {
    alert('登录失败，请检查网络连接')
  }
}

const handleRegister = async () => {
  // 表单验证
  if (!registerForm.value.userId || !registerForm.value.name || 
      !registerForm.value.password || !registerForm.value.confirmPassword) {
    alert('请填写完整信息')
    return
  }
  
  if (registerForm.value.password !== registerForm.value.confirmPassword) {
    alert('两次输入的密码不一致')
    return
  }
  
  try {
    const res = await axios.post('/api/register', {
      userId: registerForm.value.userId,
      name: registerForm.value.name,
      password: registerForm.value.password,
      role: registerForm.value.role
    })
    
    if (res.data.code === 200) {
      alert('注册成功！请登录')
      toggleMode() // 切换到登录页面
    } else {
      alert(res.data.msg || '注册失败')
    }
  } catch (error) {
    alert('注册失败，请检查网络连接')
  }
}
</script>

<style scoped>
.login-bg {
  min-height: 100vh;
  background:
    url('https://images.unsplash.com/photo-1506744038136-46273834b3fb?auto=format&fit=crop&w=1200&q=80') center/cover no-repeat,
    linear-gradient(135deg, #e0e7ff 0%, #f8fafc 100%);
  background-blend-mode: lighten;
  display: flex;
  align-items: center;
  justify-content: center;
}
.login-card {
  background: rgba(255,255,255,0.95);
  box-shadow: 0 4px 24px 0 rgba(0,0,0,0.08);
  border-radius: 12px;
  padding: 40px 32px 32px 32px;
  min-width: 340px;
  max-width: 90vw;
  margin: 0 auto;
  transition: box-shadow 0.2s;
}
.login-title {
  text-align: center;
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 28px;
  color: #333;
  letter-spacing: 2px;
}
.login-form {
  max-width: 350px;
  margin: 0 auto;
}
.el-form-item {
  margin-bottom: 22px;
}
.login-input {
  width: 100%;
  min-width: 220px;
  max-width: 300px;
  box-sizing: border-box;
}
.login-btn {
  min-width: 90px;
  margin-right: 12px;
}
.login-btn:last-child {
  margin-right: 0;
}
@media (max-width: 500px) {
  .login-card {
    padding: 24px 8px 16px 8px;
    min-width: unset;
  }
  .login-title {
    font-size: 1.3rem;
  }
  .login-input {
    min-width: unset;
    max-width: 100%;
  }
}
</style>